package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerEchoMultiThread extends Thread {

	private Socket socket;

	public ServerEchoMultiThread(Socket socket) {
		this.socket = socket;
		start();
	}

	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())), true);

			String str;
			while (true) {
				str = in.readLine();
				System.out.println("from client >> " + str);
				out.println(">> to client " + str);
				if (str.equals("END"))
					break;
			}
			System.out.println("Server is about to close the connection");
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		int port = 2501;
		try {
			ServerSocket serverS = new ServerSocket(port);
			while (true) {
				System.out.println("Server is ready !!");
				Socket socketClient = serverS.accept();
				new ServerEchoMultiThread(socketClient);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
